const ResponseUtil = require('../utils/ResponseUtil');
const moment = require('moment');

function isChinese(str) {
    return /^[\u4e00-\u9fa5]+$/.test(str);
}

module.exports = (option, app) => {
    return async function errorHandler(ctx, next) {
        let ip = ''
        try {
            ip = ctx.req.headers['x-forwarded-for'] || ctx.req.connection.remoteAddress
                || ctx.req.socket.remoteAddress || ctx.req.connection.socket.remoteAddress || ''
        } catch (e) {
        }

        try {
            console.error('path', moment().format('YYYY-MM-DD HH:mm:ss'), ip, ctx.request.path, ctx.request.body, ctx.query, ctx.params);
            ctx.app.logger.error('path', ip, ctx.request.path, ctx.request.body, ctx.query, ctx.params);
            await next();
        } catch (err) {
            console.error('error found', moment().format('YYYY-MM-DD HH:mm:ss'), ip, ctx.request.path, ctx.request.headers, ctx.request.query, JSON.stringify(ctx.request.body), err)
            ctx.app.logger.error('error found', ip, ctx.request.path, ctx.request.headers, ctx.request.query, JSON.stringify(ctx.request.body), err)
            const isChineseResult = isChinese(err.message);
            ctx.body = ResponseUtil.resError(isChineseResult ? err.message : '服务器错误，请稍后再试')
        }
    };
};
